import json
import re
import time

import requests
import sys
import os

sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

from twocaptcha import TwoCaptcha

api_key = '018549da87825c50746f28e59fb10a9e'
site_key = "85800716-F435-4981-864C-8B90602D10F7"

datas = [
    # 登录报错
    ["odepzgtmwgjp@outlook.com", "Lh123456"],  # ok
    # {"g0":{"data":{"error":"メールアドレスまたはパスワードが正しくありません。","loginDisabled":7,"redirectUrl":null,"trackingToken":null},"meta":{"version":"6a0982"}}}
    ["eweebiovmdjwyb@outlook.com", "oXdOkZ771"],
    # {"g0":{"data":{"error":"メールアドレスまたはパスワードが正しくありません。","loginDisabled":7,"redirectUrl":null,"trackingToken":null},"meta":{"version":"6a0982"}}}
    ["qebbrrhd@outlook.com", "Lh123456"],
    # {"g0":{"data":{"error":"メールアドレスまたはパスワードが正しくありません。","loginDisabled":7,"redirectUrl":null,"trackingToken":null},"meta":{"version":"6a0982"}}}
    ["ozjiricffskrz@outlook.com", "Lh123456"],
    # {"g0":{"data":{"error":"メールアドレスまたはパスワードが正しくありません。","loginDisabled":7,"redirectUrl":null,"trackingToken":null},"meta":{"version":"6a0982"}}}
    ["mcbabexaysr@outlook.com", "Lh123456"],
    # ok
    ["kamiyamatomoko52632@softbank.ne.jp", "tomoko52632"],
    # {"g0":{"data":{"error":"メールアドレスまたはパスワードが正しくありません。","loginDisabled":7,"redirectUrl":null,"trackingToken":null},"meta":{"version":"6a0982"}}}
    # ["h-wtnabe@ybb.ne.jp", "kpqkp783"],
    # ok
    # ["kpqkp783@ybb.ne.jp", "kpqkp783"],
    # 实名 Rejected
    # ['evik1113@hotmail.com', 'evik1113']
]
n = -1
email = datas[n][0]
password = datas[n][1]
print("email:", email, "password:", password)
proxies_clash = {
    'http': 'http://127.0.0.1:7890',
    'https': 'http://127.0.0.1:7890'
}
proxies_charles = {
    'http': 'http://127.0.0.1:8889',
    'https': 'http://127.0.0.1:8889'
}
proxies_none = {
    'http': None,
    'https': None,
}
proxies = proxies_none
# proxies = proxies_clash
session = requests.Session()


def init_page():
    response = session.get("https://mobi.jp.match.com/login"
                           , proxies=proxies, verify=False
                           )

    match = re.search(r'"_csrf":"(.*?)"', response.text)

    if match:
        return match.group(1)
    else:
        raise Exception("no match csrf")


def api_login(csrf, recapcha):
    headers = {
        'accept': '*/*',
        'accept-language': 'zh-CN,zh;q=0.9',
        'adrum': 'isAjax:true',
        'cache-control': 'no-cache',
        'content-type': 'application/json',
        'origin': 'https://jp.match.com',
        'pragma': 'no-cache',
        'priority': 'u=1, i',
        'referer': 'https://jp.match.com/login',
        'sec-ch-ua': '"Google Chrome";v="125", "Chromium";v="125", "Not.A/Brand";v="24"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
        'x-requested-with': 'XMLHttpRequest',
    }

    params = {
        '_csrf': csrf,
        'locale': 'ja-JP',
    }

    data = {
        'requests': {
            'g0': {
                'resource': 'auth',
                'operation': 'create',
                'params': 'login',
                'body': {
                    'email': email,
                    'password': password,
                    'rememberMe': True,
                    'submitted': False,
                    'recaptchaResponse': recapcha,
                    'reactivateUrl': 'reactivateAccount',
                    'trackingToken': None,
                },
            },
        },
        'context': {
            'locale': 'ja-JP',
            '_csrf': csrf
        },
    }

    response = session.post('https://jp.match.com/api'
                            , headers=headers
                            , params=params
                            , json=data
                            , proxies=proxies, verify=False,
                            )
    print(response)
    if response.status_code != 200:
        print("api login auth fail")
        sys.exit()
    print(response.text)
    try:
        data = response.json()
        error = data.get('g0').get('data').get('error')
        if error:
            print(f'错误： {error}')
            sys.exit()
    except Exception as e:
        print('解析失败', response.text)
    return response.json()


def get_recaptchaResponse():
    surl = "https://client-api.arkoselabs.com"
    url = "https://jp.match.com"
    solver = TwoCaptcha(api_key)

    try:
        result = solver.funcaptcha(sitekey=site_key,
                                   url=url,
                                   # url='https://mysite.com/page/with/funcaptcha',
                                   surl=surl)

    except Exception as e:
        print(f"验证码错误：{e}")
        sys.exit()

    else:
        print('result: ' + str(result))
        return result.get('code')


def get_currrent_user():
    headers = {
        'accept': '*/*',
        'accept-language': 'zh-CN,zh;q=0.9',
        'adrum': 'isAjax:true',
        'cache-control': 'no-cache',
        'priority': 'u=1, i',
        'referer': 'https://jp.match.com/logout',
        'sec-ch-ua': '"Google Chrome";v="125", "Chromium";v="125", "Not.A/Brand";v="24"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
        'x-requested-with': 'XMLHttpRequest',
    }

    params = {
        '_csrf': '4lYtAdW8-JrnaPAcsF4rzZPFzgZ1fVXfH4OI',
        'locale': 'ja-JP',
        'returnMeta': 'true',
    }

    response = requests.get('https://jp.match.com/api/current-user', params=params, cookies=cookies, headers=headers)
    return response.json()


def get_data(userId, authtoken):
    headers = {
        "accept": "*/*",
        "accept-language": "zh-CN,zh;q=0.9",
        "cache-control": "no-cache",
        "content-type": "application/json",
        "origin": "https://jp.match.com",
        "pragma": "no-cache",
        "priority": "u=1, i",
        "referer": "https://jp.match.com/profile/me/edit",
        "sec-ch-ua": "\"Google Chrome\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"
    }
    url = "https://jp.match.com/graphql"
    data = {
        "operationName": "ProfileEdit",
        "variables": {
            "userId": userId,
            "isMetric": True
        },
        "query": "query ProfileEdit($userId: String!, $isMetric: Boolean) {\n  profileEdit(userId: $userId, isMetric: $isMetric) {\n    ...ProfileEdit_LayoutData\n    __typename\n  }\n}\n\nfragment ProfileEdit_LayoutData on Profile {\n  id\n  userId\n  primaryPhoto {\n    id\n    uri\n    __typename\n  }\n  ...Profile_AccountInfo\n  ...Profile_ProfileAttributeData\n  ...Profile_SelfInfo\n  self {\n    ...ProfileEdit_EssayData\n    __typename\n  }\n  seek {\n    ...Profile_SeekSummary\n    __typename\n  }\n  photos {\n    ...Profile_Photos\n    __typename\n  }\n  userCertifications {\n    ...User_Certifications\n    __typename\n  }\n  __typename\n}\n\nfragment Profile_ProfileAttributeData on Profile {\n  profileQueueStatus\n  hasUpgradedEnhancedInterests\n  self {\n    college {\n      id\n      name\n      __typename\n    }\n    schools {\n      id\n      userId\n      schoolId\n      schoolName\n      educationLevel\n      __typename\n    }\n    hometown {\n      id\n      cityCode\n      displayName\n      __typename\n    }\n    height\n    id\n    essays {\n      id\n      essayId\n      text\n      approvalStatus\n      __typename\n    }\n    trendingEssays {\n      id\n      essayId\n      text\n      approvalStatus\n      __typename\n    }\n    pendingEssays {\n      id\n      essayId\n      text\n      approvalStatus\n      __typename\n    }\n    pendingTrendingEssays {\n      id\n      essayId\n      text\n      approvalStatus\n      __typename\n    }\n    attributes {\n      id\n      attributeId\n      answerIds\n      answersData {\n        id\n        answerId\n        answerText\n        __typename\n      }\n      weight\n      __typename\n    }\n    __typename\n  }\n  seek {\n    id\n    uHeight\n    lHeight\n    ageWeight\n    heightWeight\n    distanceWeight\n    attributes {\n      id\n      attributeId\n      answerIds\n      answersData {\n        id\n        answerId\n        answerText\n        __typename\n      }\n      weight\n      __typename\n    }\n    __typename\n  }\n  __typename\n}\n\nfragment Profile_AccountInfo on Profile {\n  handle\n  id\n  self {\n    age\n    id\n    __typename\n  }\n  __typename\n}\n\nfragment Profile_SelfInfo on Profile {\n  self {\n    id\n    gender\n    location {\n      id\n      fullName\n      country {\n        id\n        name\n        shortName\n        __typename\n      }\n      state {\n        id\n        name\n        shortName\n        __typename\n      }\n      city {\n        id\n        name\n        shortName\n        __typename\n      }\n      postalCode\n      __typename\n    }\n    hometown {\n      id\n      cityCode\n      displayName\n      __typename\n    }\n    __typename\n  }\n  __typename\n}\n\nfragment Profile_SeekSummary on ProfileSeek {\n  id\n  lAge\n  uAge\n  ageWeight\n  heightWeight\n  distanceWeight\n  gender\n  location {\n    id\n    fullName\n    city {\n      id\n      name\n      __typename\n    }\n    state {\n      id\n      name\n      shortName\n      __typename\n    }\n    country {\n      id\n      name\n      shortName\n      __typename\n    }\n    postalCode\n    __typename\n  }\n  photosOnly\n  withinRadius\n  __typename\n}\n\nfragment ProfileEdit_EssayData on ProfileSelf {\n  essays {\n    id\n    essayId\n    text\n    approvalStatus\n    __typename\n  }\n  pendingEssays {\n    id\n    essayId\n    text\n    approvalStatus\n    __typename\n  }\n  __typename\n}\n\nfragment Profile_Photos on ProfilePhotosCollection {\n  id\n  totalItems\n  items {\n    ...Profile_PhotosPhoto\n    __typename\n  }\n  __typename\n}\n\nfragment Profile_PhotosPhoto on ProfilePhoto {\n  id\n  approvalStatus\n  captionApprovalStatus\n  caption\n  isPrimary\n  ordinal\n  uri\n  isPrimaryCapable\n  __typename\n}\n\nfragment User_Certifications on UserCertificateCollection {\n  id\n  maxResults\n  totalItems\n  items {\n    id\n    certificateId\n    certificateType\n    approvalStatus\n    isVisible\n    uploadDate\n    rejectDate\n    approveDate\n    userId\n    __typename\n  }\n  __typename\n}\n"
    }
    # data = json.dumps(data, separators=(',', ':'))
    response = session.post(url, headers=headers, json=data
                            , proxies=proxies, verify=False
                            )

    if response.status_code != 200:
        print("未知错误")
        print(response.text)
        return '未知错误'
    try:
        res = response.json()
        items = res['data']['profileEdit']['userCertifications']['items']
        if items:
            return items[0]['approvalStatus']
        else:
            return '无实名信息'
    except:
        print(response.text)
        return '未知错误'


if __name__ == "__main__":
    _csrf_page = init_page()
    _csrf_cookie = session.cookies.get('_csrf')
    print('cookie', _csrf_page, _csrf_cookie)
    cookies = {
        '_csrf': _csrf_cookie,
    }
    for key, value in cookies.items():
        session.cookies.set(key, value)

    # api_create_login(_csrf_page, _csrf_cookie)
    time.sleep(0.1)
    recapcha = get_recaptchaResponse()
    # recapcha = '33117d1bda44551d8.8411444802|r=us-west-2|meta=3|metabgclr=%23ffffff|metaiconclr=%23757575|guitextcolor=%23000000|pk=85800716-F435-4981-864C-8B90602D10F7|at=40|sup=1|rid=32|ag=101|cdn_url=https%3A%2F%2Fclient-api.arkoselabs.com%2Fcdn%2Ffc|lurl=https%3A%2F%2Faudio-us-west-2.arkoselabs.com|surl=https%3A%2F%2Fclient-api.arkoselabs.com|smurl=https%3A%2F%2Fclient-api.arkoselabs.com%2Fcdn%2Ffc%2Fassets%2Fstyle-manager'
    recapcha = "a:" + recapcha
    print("校验", recapcha)
    time.sleep(0.1)
    if 'uid' in session.cookies:
        del session.cookies['uid']
    if 'authtoken' in session.cookies:
        del session.cookies['authtoken']
    login_info = api_login(_csrf_page, recapcha)
    time.sleep(0.1)
    print("登录成功", login_info)
    print('cookie', session.cookies.items())
    try:
        user_id = session.cookies.get('uid')
    except Exception as e:
        user_id = [cookie for cookie in session.cookies if cookie.name == 'uid'][-1].value

    try:
        auth_token = session.cookies.get('authtoken')
    except Exception as e:
        auth_token = [cookie for cookie in session.cookies if cookie.name == 'authtoken'][-1].value

    # authtoken
    print("uid,token", user_id, auth_token)
    res = get_data(userId=user_id, authtoken=auth_token)
    print("实名", res)
